package test.redis;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.Set;

import redis.clients.jedis.Jedis;

public class LimitLogin {
	
	static int limitSec = 5;
	
	public static void main(String[] args) {
		for(int i=0;i<10;i++)  {
			checkLogin("zhangsan");
			try {
				int x = new Random().nextInt(10);
				Thread.sleep(x * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	static boolean checkLogin(String name) {
		boolean flag = true;
		try(Jedis jedis = new Jedis("10.167.202.94", 6380)) {
			jedis.auth("123456");
			String key = "login:" + name;
			long nowTime = System.currentTimeMillis();
			long startTime = nowTime - limitSec * 1000;
			Set<String> set = jedis.zrangeByScore(key, startTime, nowTime);
			for(String s : set) {
				System.out.print(new SimpleDateFormat("HH:mm:ss").format(new Date(Long.parseLong(s))) + ",");
			}
			System.out.println();
			if(set.size() < 5) {
				jedis.zadd(key, nowTime, nowTime + "");
			} else {
				flag = false;
			}
		}
		System.out.println(new Date() + ",result=" + flag);
		return flag;
	}

}
